import React, {useEffect, useState} from 'react';
import {
  AppBar,
  Toolbar,
  Typography,
  Container,
  TextField,
  Button,
  CircularProgress, Box
} from '@mui/material';
import {getPortfolio, PortfileAsset} from "./investor/investor";
import data from "./data/imoex.json";
import {useSaveLocalStorage} from "./hooks";
import {LocalStorageKeys} from "./constants";
import { useForm } from "react-hook-form"
import { yupResolver } from '@hookform/resolvers/yup';
import { validationSumForm } from './lib/validationSumForm';
import {AssetsList} from "./components/AssetsList/AssetsList";


interface IFormInputs {
  sum: number  
}


function App() {
  const [isLoading, setIsLoading] = useState<boolean>(false)
  const [assets, setAssets] = useState<PortfileAsset[]>([])
  const {
    register,
    formState: { errors },
    handleSubmit,
  } = useForm<IFormInputs>({
        resolver: yupResolver(validationSumForm),
  })
  const { saveInLs, getFromLs } = useSaveLocalStorage()
  const capitalFromLs = getFromLs(LocalStorageKeys.CAPITAL) || 10000

  const onSubmit = ({sum}: IFormInputs) => {
    saveInLs(LocalStorageKeys.CAPITAL, String(sum))
    getAssets(Number(sum))
  }

  const getAssets = (capital: number) => {
    setIsLoading(true)
    getPortfolio(data, capital)
        .then((res: PortfileAsset[]) => setAssets(res))
        .catch(err => console.log(err))
        .finally(() => setIsLoading(false))
  }

  useEffect(() => {
    capitalFromLs && getAssets(Number(capitalFromLs))
  }, [capitalFromLs])

  return (
    <div>
      <AppBar position="static">
        <Toolbar>
          <Typography variant="h6">
            IndexInvestor
          </Typography>
        </Toolbar>
      </AppBar>
      <Container>
        <Typography variant="h5" gutterBottom style={{ marginTop: '20px' }}>
          Мой капитал
        </Typography>
        <form onSubmit={handleSubmit(onSubmit)}>
          <TextField
            variant="outlined"
            fullWidth
            error={!!Object.keys(errors).length}
            helperText={errors.sum?.message}
            label="Введите ваш капитал"
            placeholder="Например, 10000"
            style={{ marginBottom: '20px' }}
            {...register("sum")}
        />
        <Button variant='outlined' type='submit'>Отправить</Button>
        </form>
        {isLoading
            ? <Box display="flex" justifyContent="center" alignItems="center" height="100px">
              <CircularProgress />
            </Box>
            : <AssetsList assets={assets} />
        }
      </Container>
    </div>
  );
}

export default App;
